﻿using Blog190311.Areas.Back.Models;
using Blog190311.Areas.Back.Models.DAL;
using Blog190311.Models.DBModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace Blog190311.Areas.Back.Controllers
{
    [Authorize]//禁止直接访问
    public class HomeController : Controller
    {
        // GET: Back/Home
        public ActionResult Index()//后台首页
        {
            return View();
        }

        [AllowAnonymous]//允许直接访问
        [HttpGet]
        public ActionResult Login()//登录
        {
            return View();
        }

        [AllowAnonymous]
        [HttpPost]
        public ActionResult Login(string username, string password)
        {
            HomeService homeService = new HomeService();
            User user = homeService.GetUser(username);
            if (user == null)
            {
                return Json(new UIResult() { Success = false, Message = "用户名不存在" });
            }
            else
            {
                if (user.Password == password)
                {
                    FormsAuthentication.SetAuthCookie(username, false);
                    user.LastLoginTime = DateTime.Now.ToString();
                    homeService.UpdateUser(user);
                    return Json(new UIResult() { Success = true });
                }
                else
                {
                    return Json(new UIResult() { Success = false, Message = "密码不正确" });
                }
            }
        }

        public ActionResult SignOut()//安全退出
        {
            FormsAuthentication.SignOut();//注销通行证
            return Redirect("~/Back/Home/Login"); //转到登录页面
        }

        public ActionResult ChangePwd(string username)//修改密码
        {
            HomeService homeService = new HomeService();
            User user = homeService.GetUserByUserName(username);
            return View(user);
        }

        public ActionResult UpdateUser(User user)
        {
            HomeService homeService = new HomeService();
            int num = homeService.UpdateUser(user);
            return Content(num.ToString());
        }

        public ActionResult Self()//个人信息
        {
            return View();
        }

        public ActionResult GetUserSelf()
        {
            HomeService homeService = new HomeService();
            List<User> user = homeService.GetUser();
            return Json(new { code = 0, msg = "", count = 1, data = user }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Welcome()//欢迎页
        {
            return View();
        }
    }
}